class User < ActiveRecord::Base

	before_create :create_activation_digest
	has_many :posts,dependent: :destroy
	has_many :images,dependent: :destroy
	has_many :likes ,dependent: :destroy
	# 关注者都放在follower列
	# 被关注者都在followed列
	has_many :active_relationships,class_name: "Relationship",foreign_key: "follower_id",dependent: :destroy
	has_many :passive_relationships,class_name: "Relationship",foreign_key: "followed_id",dependent: :destroy

	has_many :followers, through: :passive_relationships ,source: :follower
	has_many :following, through: :active_relationships ,source: :followed

	# attr_accessor :tag_list
	attr_accessor :remember_token,:activation_token,:reset_token

	validates :name,presence:{message:'昵称不能为空'},length: {maximum:20,message:'姓名太长,不能超过10个汉字或者20个字母'}
	# valid_email= /[\w+]+@[a-z]+\.[a-z]+/
	validates :email, presence:true,length:{maximum:255},uniqueness:{case_sensitive: false}
	has_secure_password
	validates :password,presence: {message:'密码不能为空'}, length: {message:'密码太短,必须大于6个字母或数字的组合',minimum: 6}



	def tag_list=(tags)
		UsersHelper::RuntimeRegistry.tag_lists = tags
	end
	def tag_list
		UsersHelper::RuntimeRegistry.tag_lists
	end
	def User.digest(string)
		cost=ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
		BCrypt::Password.create(string,cost: cost)
	end

	def User.new_token
		SecureRandom.urlsafe_base64
	end

#每次用户登陆或注册后就会生成一个随机字符串remember_token对应的摘要放入数据库
	def remember
		self.remember_token= User.new_token
		# 用来生成cookies中用到的随即字符串
		# 随机字符串的摘要存入数据库
		update_attribute(:remember_digest,User.digest(remember_token))

	end

	def authenticated?(attribute,token)
		digest= self.send("#{attribute}_digest")
		return false if digest.nil?
		BCrypt::Password.new(digest).is_password?(token)
	end

	def forget
		update_attribute(:remember_digest,nil)
	end

	def create_activation_digest
		self.activation_token=User.new_token
		self.activation_digest=User.digest(activation_token)
	end

	def create_reset_digest
		self.reset_token=User.new_token
		update_attribute(:activation_digest,User.digest(reset_token))
		update_attribute(:activation_sent_at,Time.zone.now)
	end
	# 关注
	def follow(other_user)
		active_relationships.create(followed_id: other_user.id)
	end

	# 取消关注某人
	def un_follow(other_user)
		active_relationships.find_by(followed_id: other_user.id).destroy
	end

	#user.following 当前用户关注的人
	def following?(other_user)
		following.include?(other_user)
	end

	def feeds
		following_ids="SELECT followed_id FROM relationships WHERE follower_id = :user_id "

		Post.where("user_id in (#{following_ids}) OR user_id = :user_id",user_id: id)
	end

	def tags_count(name)
		post_ids="SELECT id FROM posts WHERE user_id = :user_id "
		Tag.where("post_id in (#{post_ids} AND name = :name)",user_id: id,name: name).count
	end

end
